package uit.nfcmenu.view;

import java.util.Collections;
import java.util.List;

import uit.nfcmenu.activity.BaseActivity;
import uit.nfcmenu.db.model.OrderModel;
import uit.nfcmenu.db.model.OrderUIModel;
import uit.nfcmenu.manager.AssetsManager;
import uit.nfcmenu.util.CommConstant;
import uit.nfcmenu.util.ImageLoader;
import uit.nfcmenu.util.UiUtilities;
import uit.nfcmenu.util.Utilities;
import uit.nfcmenu.webservice.JSONParser;
import uit.nfcmenu.webservice.PreferenceHelper;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Chronometer;
import android.widget.Chronometer.OnChronometerTickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import uit.nfcmenu.R;

/* Databind data for ListItemModel */

// The adapter class!
public class OrderAdapter extends BaseAdapter {
	String tag = OrderAdapter.class.getSimpleName();

	private Context mContext;
	private LayoutInflater mInflater;
	private List<OrderModel> mModels;

	String mLanguage;
	ImageLoader mImageLoader;
	private OrderModel currentOrder;
	OrderUIModel myOrderUI;
	
	public OrderAdapter(Context context, OrderUIModel orderUI) {
		mContext = context;
		mInflater = LayoutInflater.from(mContext);
		mModels = orderUI.listorders;
		myOrderUI = orderUI;
		mLanguage = PreferenceHelper.loadLanguage(mContext);
		mImageLoader = new ImageLoader(mContext, true);
	}

	public List<OrderModel> getModels() {
		return mModels;
	}

	public void setModels(OrderUIModel orders) {
		// Log.w(tag, "setModels(models): "+models.size()+"elements");
		myOrderUI = orders;
		mModels = myOrderUI.listorders;
	}

	// get total amount of list items
	@Override
	public int getCount() {
		return (mModels != null) ? mModels.size() : 0;
	}

	// get the list item given its position
	@Override
	public Object getItem(int position) {
		return (mModels != null && position >= 0 && position < mModels.size()) ? mModels
				.get(position) : null;
	}

	// get the list item's ItemModelName given its position
	@Override
	public long getItemId(int position) {
		if (mModels.get(position) != null) {
			return mModels.get(position).getId();
		}
		return 0;
	}

	// Project view of the list
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		/// declare view holder to hold custom list contents
		final ViewHolder holder = new ViewHolder();

		// if (convertView == null) {
		convertView = mInflater.inflate(R.layout.inflater_order, null);
		holder.img = (ImageView) convertView.findViewById(R.id.thumbnail);
		holder.tvItem = (TextView) convertView.findViewById(R.id.tvItem);
		holder.tvTable = (TextView) convertView.findViewById(R.id.tvTable);
		holder.tvQuantity = (TextView) convertView.findViewById(R.id.tvQuantity);
		holder.tvTime = (Chronometer) convertView.findViewById(R.id.temp);
		holder.btnStatus = (ImageButton) convertView.findViewById(R.id.btnStatus);
		// holder.tvComment = (TextView)convertView.findViewById(R.id.txtComment);
		holder.row = (LinearLayout) convertView.findViewById(R.id.row);
		holder.imgComment = (ImageView) convertView.findViewById(R.id.imgComment);
		holder.tvTimeShow = (TextView) convertView.findViewById(R.id.tvTime);
		// convertView.setTag(holder);
		// } else {
		// holder = (ViewHolder) convertView.getTag();
		// }

		holder.row.setSelected(position % 2 != 0);
		AssetsManager.setCommonAppFont(mContext, holder.tvItem);
		AssetsManager.setCommonAppFont(mContext, holder.tvQuantity);
		AssetsManager.setCommonAppFont(mContext, holder.tvTable);
		AssetsManager.setCommonAppFont(mContext, holder.tvTime);

		/// set data to view		
		OrderModel model = (OrderModel) getItem(position);
		if (model != null) {
			// set name
			String itemName = "";
			if (CommConstant.item != null) {
				try {
					itemName = CommConstant.item.get(model.getItemID());
					holder.tvItem.setText(JSONParser.getStringByLanguage(
							itemName, mLanguage));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// set image
			try {
				int menuID = CommConstant.itemsMenus.get(model.getItemID());
				String link = CommConstant.menuImgLinks.get(menuID);
				mImageLoader.displayImage(link, holder.img, R.drawable.logo);
			} catch (Exception e) {
				Log.e(tag, "Exception: ", e);
			}
			
			if(myOrderUI.getItemBitmap(model.getItemID())!=null)
			holder.img.setImageBitmap(myOrderUI.getItemBitmap(model.getItemID()));
			else
			holder.img.setImageResource(R.drawable.logo);	
			
			holder.tvTable.setText("" + model.getTableNo());
			holder.tvQuantity.setText("" + model.getQuantity());

			// set time
			holder.tvTime.setBase(Utilities.getTimeCurrentCounter(model.getDate()));
			holder.tvTime.start();
			// TODO optimize this
			holder.tvTime.setOnChronometerTickListener(new OnChronometerTickListener() {
				boolean fistTime = true;
					@Override
					public void onChronometerTick(Chronometer chronometer) {
						long temp = (SystemClock.elapsedRealtime() - chronometer
								.getBase()) / 1000;
						int sec = (int) temp % 60;
						if (fistTime || sec == 0) {
							fistTime = false;
							String time = "";
							time = Utilities.portTimeToString(temp);
							holder.tvTimeShow.setText(time);
						}
					}
				});

			// set status
			holder.btnStatus.setVisibility(View.VISIBLE);
			holder.btnStatus.setImageResource(model.getStatusIcon(mContext));
			holder.btnStatus.setTag(model.getStatus());
			holder.btnStatus.setOnClickListener(onStatus_click(position));

			// comment
			final String cm = model.getComment().trim();
			if (cm != null && !"".equals(cm)) {
				holder.imgComment.setVisibility(View.VISIBLE);
				holder.imgComment.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						UiUtilities.popupAlertMessage(mContext,
								R.string.comment, cm, R.string.ok);
					}
				});
			} else {
				holder.imgComment.setVisibility(View.GONE);
				/*holder.imgComment.setBackgroundResource(android.R.color.transparent);
				holder.imgComment.setImageResource(android.R.color.transparent);*/
			}
		}

		return convertView;
	}

	String[] mstrings;

	private OnClickListener onStatus_click(final int position) {
		return new OnClickListener() {

			@Override
			public void onClick(View v) {
				final ImageButton btn = (ImageButton) v;
				
				// Log.w(tag,
				// "onStatus_click() btn "+btn.getText().toString()+" ~ "+index);
				currentOrder=mModels.get(position);
				int n = 0;
				int j = 0;
				// FIXME order state // check
				// filter values of order depend on waiter or chef
				if (CommConstant.isWaiter) { // waiter
					n = CommConstant.mOrderStatus.length - 2;
					mstrings = new String[n];
					for (int i = 0; i < n; i++) {
						if (j == CommConstant.STATUS_COOKING) {
							j++; // also pass j == CommConstant.STATUS_COOKED
						}
						if (j == CommConstant.STATUS_COOKED) {
							j++;
						}
						mstrings[i] = CommConstant.mOrderLanguage[j];
						j++;
					}
				} else { // chef
					n = CommConstant.mOrderStatus.length - 1;
					mstrings = new String[n];
					for (int i = 0; i < n; i++) {
						if (j == CommConstant.STATUS_SERVED) {
							j++;
						}
						mstrings[i] = CommConstant.mOrderLanguage[j];
						j++;
					}
				}
				int index =-1;
				for(int i=0;i<mstrings.length;i++){
					String statusLanguage=CommConstant.getStatusLanguage(currentOrder.getStatus());
					if(mstrings[i].toLowerCase().equals(statusLanguage.toLowerCase())){
						index=i;
						break;
					}
				}
				// show alert for chooses
				UiUtilities.popAlert2Choose(mContext, R.string.status,
						mstrings, index, R.string.ok,
						onDialogOk_click(position, btn, mstrings),
						R.string.cancel, null);
			}
		};
	}

	private android.content.DialogInterface.OnClickListener onDialogOk_click(
			final int position, final ImageButton btn, final String[] strings) {
		return new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				int selectedPosition = ((AlertDialog) dialog).getListView()
						.getCheckedItemPosition();
				String value = mstrings[selectedPosition];

				if (!value.equals(mContext.getString(R.string.status_deny))) {
					currentOrder = mModels.get(position);
					mModels.get(position).setStatus(CommConstant.getStatusViaLanguage(value));
					currentOrder.setStatus(CommConstant.getStatusViaLanguage(value));
					// OrderManager.getInstance(mContext).currentOrder
					// .setStatus(CommConstant.mOrderStatus[selectedPosition]);
					if (CommConstant.isWaiter) { // waiter
						String status_served = mContext.getString(R.string.status_served);
						String status_done = mContext.getString(R.string.status_done);
						String status_deny = mContext.getString(R.string.status_deny);
						if (value.equals(status_served)	|| value.equals(status_done) || value.equals(status_deny)) {
							mModels.remove(position);
						}
					} else { // Chef
						String status_new = mContext.getString(R.string.status_new);
						String status_cooking = mContext.getString(R.string.status_cooking);
						if (!value.equals(status_new) && !value.equals(status_cooking)) {
							mModels.remove(position);
						}
					}
					((BaseActivity) mContext).saveData();
					btn.setTag(currentOrder.getStatus());
					btn.setImageResource(currentOrder.getStatusIcon(mContext));
					 //
//					 btn.setText(CommConstant.mOrderStatus[selectedPosition]);
					notifyDataSetChanged();
				} else {
					makeDeny(position, value);
				}
			}
		};
	}

	private void makeDeny(final int pos,final String value) {
		// TODO popup alert to input "why deny"
		View layout = mInflater.inflate(R.layout.chef_popup_comment, null);
		final EditText tvComment = (EditText) layout.findViewById(R.id.txtComment);
		// ttnlan: fix bug #90890 comment: not show comment of waiter in here
//		tvComment.setText(mModels.get(pos).getComment());

		UiUtilities.popAlert2Choose(mContext, layout, R.string.comment, -1,
				R.string.ok, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						String comment = tvComment.getText().toString();
						// Work with Database to save Comment
						mModels.get(pos).setComment(comment);
						currentOrder = mModels.get(pos);
						currentOrder.setStatus(CommConstant.getStatusViaLanguage(value));
						mModels.remove(pos);
						// TODO deny order
						if (mContext instanceof BaseActivity) {
							((BaseActivity) mContext).saveData();
						}
						notifyDataSetChanged();
					}
				}, R.string.cancel, null);
	}

	public void changeLanguage(String language) {
		mLanguage = language;
		notifyDataSetChanged();

	}

	// view holder model
	class ViewHolder {
		ImageView img;
		TextView tvItem;
		TextView tvTable;
		TextView tvQuantity;
		Chronometer tvTime;
		ImageButton btnStatus;
		// TextView tvComment;
		LinearLayout row;
		TextView tvDeny;
		ImageView imgComment;
		TextView tvTimeShow;
	}

	// private void getDenyButtonText(String status, Button btn) {
	// if (status != null
	// && (OrderStates.valueOf(status) == OrderStates.NEW
	// || OrderStates.valueOf(status) == OrderStates.COOKING)) {
	// // btn.setText(CommConstant.status.get(OrderStates.DENY.name()));
	// btn.setText(OrderStates.DENY.name());
	// btn.setBackgroundDrawable((ctx.getResources()
	// .getDrawable(R.drawable.corner_red_gradient)));
	//
	// } else if (OrderStates.valueOf(status) == OrderStates.COOKED) {
	// // btn.setText(CommConstant.status.get(OrderStates.DONE.name()));
	// btn.setText(OrderStates.DONE.name());
	// btn.setBackgroundDrawable((ctx.getResources()
	// .getDrawable(R.drawable.corner_green_gradient)));
	//
	// } else {
	// btn.setVisibility(View.INVISIBLE);
	// }
	// }

	// private void convert(ArrayList<OrderModel> input) {
	// mArrItemModelsList = new ArrayList<OrderChef>();
	// for (int i = 0; i < input.size(); i++) {
	// OrderChef model = new OrderChef(input.get(i));
	// mArrItemModelsList.add(model);
	// }
	// }

	// ===================================
	// Sort
	// ===================================

	public void sort(int sortMode) {
		OrderModel.sortMode = sortMode;
		Collections.sort(mModels);
		notifyDataSetChanged();
		notifyDataSetInvalidated();
	}

	public void selectSort() {
		String[] strings = { "Name", "Table", "Quantity", "Time" };
		UiUtilities.popAlert2Choose(mContext, R.string.status, strings, 0,
				R.string.ok, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						int selectedPosition = ((AlertDialog) dialog)
								.getListView().getCheckedItemPosition();
						if (selectedPosition == 0) {
							sort(OrderModel.SORT_BY_NAME);
						} else if (selectedPosition == 1) {
							sort(OrderModel.SORT_BY_TABLE);
						} else if (selectedPosition == 2) {
							sort(OrderModel.SORT_BY_QUANTITY);
						} else if (selectedPosition == 3) {
							sort(OrderModel.SORT_BY_TIME);
						}
					}
				}, R.string.cancel, null);
	}

	public OrderModel getCurrentModel() {
		return currentOrder;
	}
}
